package com.fourGirlsAndADude.mobileDRT;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;

import com.att.intern.webservice.Incident;
import com.att.intern.webservice.Webservice.TokenInvalidException;

import android.R.animator;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ListActivity;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.widget.ArrayAdapter;
import android.widget.SearchView;
import android.R.menu;

public class SearchableActivity extends ListActivity {
	private String geoloc;
	private String username;
	private String token;
	private String authType;
	private RetrieveInfo retrieveInfo;
	private SearchResults searchResults;
	private String query;
	private ArrayAdapter<String> buildingNames;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_geolocation_search);

		Intent intent = getIntent();

		// Get values passed on by previous intent
		username = intent.getStringExtra("USER_NAME");
		token = intent.getStringExtra("TOKEN_ID");
		authType = intent.getStringExtra("AUTHORIZATION_TYPE");

		// Get the intent, verify the action and get the query
		retrieveInfo = new RetrieveInfo();
		if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
			query = intent.getStringExtra(SearchManager.QUERY);
			buildingNames = doMySearch(query);
		}

		setListAdapter(buildingNames);

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.geolocation_search, menu);
		ActionBar actionBar = getActionBar();
		//actionBar.setTitle(R.string.header);
		//actionBar.setSubtitle(R.string.subheader1);
		// Get the SearchView and set the searchable configuration
		SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
		SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
		// Assumes current activity is the searchable activity
		//searchView.setSearchableInfo(searchManager
				//.getSearchableInfo(getComponentName()));
		// searchView.setIconifiedByDefault(false);
		return true;
	}

	private ArrayAdapter<String> doMySearch(String query) {
		retrieveInfo.execute(query);
		searchResults = retrieveInfo.searchResults;
		ArrayAdapter<String> buildingNames = null;
		// To create seperators use android.amberfog.com/?p=296
		if (searchResults != null) {
			if (searchResults.getIsOpen()) {
				buildingNames = new ArrayAdapter<String>(
						SearchableActivity.this,
						android.R.layout.simple_list_item_1,
						searchResults.getBuildingNames());
			} else {
				buildingNames = new ArrayAdapter<String>(
						SearchableActivity.this,
						android.R.layout.simple_list_item_1,
						searchResults.getBuildingNames());
			}
		} else if (searchResults == null) {
			Intent intent = new Intent(getBaseContext(), LoginActivity.class);
			intent.putExtra("LOGGED_OUT", true);
			startActivity(intent);
			finish();
		} 
		return buildingNames;
	}

	private class RetrieveInfo extends AsyncTask<String, Void, Boolean> {
		private SearchResults searchResults;

		@Override
		protected Boolean doInBackground(String... arg0) {
			new LoginActivity();
			// TODO Auto-generated method stub
			final Hashtable<Integer, String> GLCINFO = LoginActivity.webService
					.getGLCInfo();
			if (arg0.equals("") || arg0 == null || arg0.length < 4
					|| arg0.length > 12) {

			} else {

				// if(geolocint) does not exist in the hashtable, start retrieve
				// info from hashtable
				// check if this glc exists as a key in the hashtable
				// else
				Enumeration<Integer> glckeys = GLCINFO.keys();
				boolean found = false;
				while (glckeys.hasMoreElements()) {
					Integer element = (Integer) glckeys.nextElement();
					String elem = Integer.toString(element);
					if (geoloc.equals(elem)) {
						found = true;
						break;
					}
				}
				if (found) {// glc is valid
					int geolocint = Integer.parseInt(geoloc);// converting
					try {
						ArrayList<Incident> locations = LoginActivity.webService
								.geolocSearch(token, geolocint);
						if (locations.size() > 0) {
							searchResults = new SearchResults(locations);
						} else {
							searchResults = new SearchResults(GLCINFO);
							searchResults.setGeoloc(geolocint);
						}
					} catch (TokenInvalidException e) {
						searchResults = null;
					}
				}
			}
			// ArrayList<Incident> incidents = LoginActivity.webService.
			return null;
		}
	}

	private class SearchResults {
		private ArrayList<Incident> incidents = new ArrayList<Incident>();
		private ArrayList<String> buildingNames = new ArrayList<String>();
		private String[] buildingOpenInfo = new String[5];
		private String[] buildingClosedInfo = new String[3];
		private Hashtable<Integer, String> glcInfo;
		private Boolean isOpen;

		public SearchResults(ArrayList<Incident> incidents) {
			this.incidents = incidents;
			buildingNames = populateBuildingNames(incidents);
			isOpen = true;
		}

		public SearchResults(Hashtable<Integer, String> glcInfo) {
			this.glcInfo = glcInfo;
			isOpen = false;
		}

		private ArrayList<String> populateBuildingNames(
				ArrayList<Incident> incidents) {
			ArrayList<String> buildingNames = new ArrayList<String>();
			for (Incident incident : incidents) {
				buildingNames.add(incident.getBuildingName());
			}
			return buildingNames;
		}

		private ArrayList<String> populateBuildingNames(String glcInfo) {
			ArrayList<String> buildingNames = new ArrayList<String>();
			for (Incident incident : incidents) {
				buildingNames.add(incident.getBuildingName());
			}
			return buildingNames;
		}

		public String[] getBuildingOpenInfo(int position) {
			Incident incident = incidents.get(position);
			buildingOpenInfo[0] = "Record Number: " + incident.getRecNumber();
			buildingOpenInfo[1] = "GLC: " + incident.getGeoLoc();
			buildingOpenInfo[2] = "Event Name: " + incident.getEventName();
			buildingOpenInfo[3] = "Status: " + incident.getStatusNotes();
			buildingOpenInfo[4] = "Work Record Number: "
					+ incident.getWorkReqNumber();
			return buildingOpenInfo;
		}

		public String[] getBuildingClosedInfo(int key) {
			String info = glcInfo.get(key);
			String[] values = info.split("~");

			buildingClosedInfo[0] = "Address: " + values[3];
			buildingClosedInfo[1] = "State: " + values[0];
			buildingClosedInfo[2] = "PM: " + values[1];
			return buildingClosedInfo;
		}

		public void setGeoloc(int geoloc) {
			String info = glcInfo.get(geoloc);
			buildingNames = populateBuildingNames(info);
		}

		public ArrayList<String> getBuildingNames() {
			return buildingNames;
		}

		public boolean getIsOpen() {
			return isOpen;
		}

	}
}
